package org.dxy.middleware.dynamic.thread.pool.infrastructure.adapter;

import lombok.extern.slf4j.Slf4j;
import org.dxy.middleware.dynamic.thread.pool.domain.model.ThreadPoolAggregate;
import org.dxy.middleware.dynamic.thread.pool.domain.port.IDynamicThreadPoolService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ description:
 * @ author: dxy
 * @ createTime: 2025/10/3 11:57
 */
@Slf4j
public class DynamicThreadPoolService implements IDynamicThreadPoolService {
    private final String appName; // 当前应用名称
    private final Map<String, ThreadPoolExecutor> executorMap; // key: poolName

    public DynamicThreadPoolService(String appName, Map<String, ThreadPoolExecutor> executorMap) {
        this.appName = appName;
        this.executorMap = new ConcurrentHashMap<>(executorMap); // 保证线程安全
    }

    public void refresh(ThreadPoolAggregate aggregate) {
        if (null == aggregate || !appName.equals(aggregate.getAppName())) return;

        String poolName = aggregate.getThreadPoolName();
        ThreadPoolExecutor executor = executorMap.get(poolName);

        if (null == executor) return;

        executor.setCorePoolSize(aggregate.getCorePoolSize());
        executor.setMaximumPoolSize(aggregate.getMaximumPoolSize());

    }
}
